package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;


    @Override
    public UserVo login(LoginDto loginDto) {
        //1. 根据用户名查询用户
        User user =userMapper.selectByUserName(loginDto.getUsername());
        //2.判断用户是否为空
        if(ObjectUtil.isEmpty(user)){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //3.判断账户是否被禁用
        if(user.getDataState().equals(SuperConstant.DATA_STATE_1)){
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }
        //4.判断密码是否正确
        if (!BCrypt.checkpw(loginDto.getPassword(), user.getPassword())){
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }
        UserVo userVo = BeanUtil.toBean(user,UserVo.class);
        //5.密码脱敏
        userVo.setPassword("");

        Map<String,Object> claims = new HashMap<>();
        claims.put("currentUser", JSONUtil.toJsonStr(userVo));

        //6.根据用户生成JWT
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);
        userVo.setUserToken(token);

        return userVo;
    }
}
